package logic

import (
	"context"
	"k8s.io/apimachinery/pkg/util/rand"
	"xialou_platform/app/cryptx"
	"xialou_platform/app/requestx"
	"xialou_platform/services/system/rpc/systemClient"

	"xialou_platform/services/system/api/internal/svc"
	"xialou_platform/services/system/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) UserAddLogic {
	return UserAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserAddLogic) UserAdd(req *types.UserReq) error {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	salt := rand.String(12)
	passwd := cryptx.PasswordEncrypt(salt, req.Phone)

	_, err = l.svcCtx.SystemRpc.SysUserAdd(l.ctx, &systemClient.SysUser{
		Role:     req.Role,
		Avatar:   req.Avatar,
		Name:     req.Name,
		Password: passwd,
		Salt:     salt,
		Gender:   req.Gender,
		Email:    req.Email,
		Phone:    req.Phone,
		CreateBy: uid,
		UpdateBy: uid,
	})
	if err != nil {
		return err
	}

	return nil
}
